<template>
  <div class="app-container" v-loading="loading" element-loading-text="拼命加载中">
    <div class="user_list">
      <div class="sx_top">
        <span class="top_span2" style="margin-right: 14px">用户名</span>
        <el-select size="mini" v-model="info.userName" clearable filterable style="width: 240px;margin-right: 14px;">
          <el-option v-for="item in list" :value="item.userName" :label="item.userName" :key="item.id"></el-option>
        </el-select>
        <span class="top_span2" style="margin-right: 14px">邮箱</span>
        <el-select size="mini" v-model="info.email" clearable filterable style="width: 240px;margin-right: 14px;">
          <el-option v-for="item in emailList" :value="item.email" :label="item.email" :key="item.id"></el-option>
        </el-select>
        <span class="top_span2" style="margin-right: 14px">手机号</span>
        <el-select size="mini" v-model="info.mobilePhone" clearable filterable style="width: 240px;margin-right: 14px;">
          <el-option v-for="item in mobilePhoneList" :value="item.mobilePhone" :label="item.mobilePhone"
            :key="item.id"></el-option>
        </el-select>
        <span class="top_span2" style="margin-right: 14px; margin-left: 14px">创建时间：</span>
        <el-date-picker clearable v-model="info.createTime" size="mini" type="date" :picker-options="options"
          placeholder="请选择" style="width: 240px;" />
        <span class="top_span2" style="margin-right: 14px; margin-left: 14px">修改时间：</span>
        <el-date-picker clearable v-model="info.updateTime" size="mini" type="date" :picker-options="options"
          placeholder="请选择" style="width: 240px;" />
        <div style="margin-top: 14px">
          <el-button size="mini" style="margin-right: 10px" type="primary" @click="handleClickSearch">查 询</el-button>
          <el-button size="mini" @click="handleReset" style="margin-right: 10px">重 置</el-button>
          <el-button size="mini" type="primary" @click="addClick">添加新用户</el-button>
        </div>
      </div>
      <div class="juads_div">
        <div style="margin-bottom: 12px">
        </div>
        <div class="table_div">
          <el-table :data="newDataList" height="calc(100vh - 380px)"
            style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
          background: 'rgba(250, 250, 250, 1)',
          textAlign: 'center',
        }">
            <el-table-column prop="id" label="序号" />
            <!-- <el-table-column prop="avatar" label="头像">
              <template slot-scope="scope">
                <el-image style="width: 25px; height: 25px;" :src="scope.row.avatar"
                  :preview-src-list="[scope.row.avatar]"></el-image>
              </template>
            </el-table-column> -->
            <el-table-column prop="userName" label="用户名" />
            <el-table-column prop="nickName" label="昵称" />
            <el-table-column prop="mobilePhone" label="手机号" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="createTime" label="创建时间" :formatter="handleFormatter" />
            <el-table-column prop="updateTime" label="更新时间" :formatter="handleFormatter2" />
            <el-table-column label="操作" width="200px" fixed="right">
              <template slot-scope="scope">
                <span @click="handleView(scope.row)" style="
                    color: #409eff;
                    cursor: pointer;
                    user-select: none;
                  ">修改</span>
              </template>
            </el-table-column>
          </el-table>
          <div class="fenye_div">
            <el-pagination background :current-page="pageNo" :page-sizes="[10, 20, 30, 40, 50, 60]"
              :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="count"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>
      <el-drawer :wrapperClosable="false" size="40%" title="添加新用户" :visible.sync="addIsShow"
        :close-on-press-escape="false">
        <div style="box-sizing: border-box;padding: 20px;overflow: hidden;">
          <el-form :model="infoForm" :rules="infoFormRules" ref="infoForm" label-width="100px">
            <el-form-item v-if="type == 'add'" label="用户名" prop="userName">
              <el-input v-model="infoForm.userName" clearable></el-input>
            </el-form-item>
            <el-form-item v-if="type == 'add'" label="密码" prop="password">
              <el-input v-model="infoForm.password" clearable></el-input>
            </el-form-item>
            <template v-if="type == 'edit'">
              <el-form-item label="旧密码" prop="oldPassword">
                <el-input v-model="infoForm.oldPassword" clearable></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="infoForm.newPassword" clearable></el-input>
              </el-form-item>
            </template>
            <el-form-item label="昵称" clearable>
              <el-input v-model="infoForm.nickName"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="infoForm.mobilePhone" clearable></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="infoForm.email" clearable></el-input>
            </el-form-item>
          </el-form>
          <div class="btn">
            <el-button style="width: 120px;margin-left: 20px;" @click="addIsShow = false">取 消</el-button>
            <el-button type="primary" style="width: 120px;margin-left: 50px;" @click="handleCickEnter">确 定</el-button>
          </div>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
  import { getUserList, addUser, editUser, editPassWord } from "@/api/user";

  export default {
    data() {
      return {
        mobilePhoneList: [],
        count: 0,
        emailList: [],
        options: {
          // 时间不能大于当前时间
          disabledDate: time => {
            return time.getTime() > Date.now();
          },
          selectableRange: "00:00:00 - 23:59:59"
        },
        loading: false,
        infoFormRules: {
          // 用户名
          userName: [
            { required: true, message: "请输入用户名", trigger: "blur" }
          ],
          // 密码
          password: [
            { required: true, message: "请输入密码", trigger: "blur" }
          ],
          // 旧密码
          oldPassword: [
            { required: true, message: "请输入旧密码", trigger: "blur" }
          ],
          // 新密码
          newPassword: [
            { required: true, message: "请输入新密码", trigger: "blur" }
          ],
          // 昵称
          nickName: [
            { required: true, message: "请输入昵称", trigger: "blur" }
          ],
          // 手机号
          mobilePhone: [
            { required: true, message: "请输入手机号", trigger: "blur" },
            {
              pattern: /^1[3-9][0-9]\d{8}$/,
              message: "请输入正确的手机号格式",
              trigger: "blur"
            }
          ],
          // 邮箱
          email: [
            { required: true, message: "请输入邮箱", trigger: "blur" },
            {
              pattern: /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/,
              message: "请输入正确的邮箱格式",
              trigger: "blur"
            }
          ],
        },
        infoForm: {
          userName: "",
          password: "",
          nickName: "",
          mobilePhone: "",
          email: "",
          avatar: "",
        },
        addIsShow: false,
        info: {
          userName: "",
          email: "",
          mobilePhone: "",
          createTime: "",
          updateTime: "",
        },
        list: [],
        newDataList: [],
        pageNo: 1,
        pageSize: 10,
        type: "",
      };
    },
    created() {
      this.getUserList();
    },
    methods: {
      // 修改用户
      async editUser() {
        try {
          const data = {
            id: this.infoForm.id,
            nickName: this.infoForm.nickName,
            mobilePhone: this.infoForm.mobilePhone,
            email: this.infoForm.email,
            avatar: ""
          };
          const { code } = await editUser(data);
          if (code == 0) {
            const passCode = await this.editPassWord();
            if (passCode == 0) {
              this.$message.success("修改成功");
              this.addIsShow = false;
              this.getUserList();
            }
          }
        } catch (error) {
          console.log(error);
        }
      },
      // 修改密码
      async editPassWord() {
        try {
          const data = {
            userId: String(this.infoForm.id),
            oldPassword: this.infoForm.oldPassword,
            newPassword: this.infoForm.newPassword
          };
          const { code } = await editPassWord(data);
          return code;
        } catch (error) {
          console.log(error);
        }
      },
      handleView(row) {
        this.type = "edit";
        this.infoForm = {
          id: row.id,
          userId: row.id,
          userName: row.userName,
          password: row.password,
          nickName: row.nickName,
          mobilePhone: row.mobilePhone,
          email: row.email,
          avatar: row.avatar,
        };
        this.addIsShow = true;
      },
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.getUserList();
      },
      handleCurrentChange(pageNo) {
        this.pageNo = pageNo;
        this.getUserList();
      },
      async addUser() {
        try {
          const { code } = await addUser(this.infoForm);
          if (code == 0) {
            this.$message.success("创建成功");
            this.addIsShow = false;
            this.getUserList();
          }
        } catch (error) {
          console.log(error);
        }
      },
      handleCickEnter() {
        this.$refs["infoForm"].validate((valid) => {
          if (valid) {
            if (this.type == "add") {
              this.addUser();
            } else if (this.type == "edit") {
              this.editUser();
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      addClick() {
        this.type = "add";
        this.infoForm = {
          userName: "",
          password: "",
          nickName: "",
          mobilePhone: "",
          email: "",
          avatar: "",
        };
        this.addIsShow = true;
      },
      // 重置
      handleReset() {
        this.info = {
          userName: "",
          email: "",
          mobilePhone: "",
          createTime: "",
          updateTime: "",
        };
        this.newDataList = JSON.parse(JSON.stringify(this.list));
      },
      // 查询
      handleClickSearch() {
        if (this.info.userName.length || this.info.email.length || this.info.mobilePhone.length || String(this.info.createTime).length || String(this.info.updateTime).length) {
          const userNameList = this.info.userName.length > 0 ? this.list.filter(item => item.userName == this.info.userName) : JSON.parse(JSON.stringify(this.list));
          const emailList = this.info.email.length > 0 ? userNameList.filter(item => item.email == this.info.email) : userNameList;
          const mobilePhoneList = this.info.mobilePhone.length > 0 ? emailList.filter(item => item.mobilePhone == this.info.mobilePhone) : emailList;
          const createTimeList = String(this.info.createTime).length > 0 ? mobilePhoneList.filter(item => item.createTime == this.formatterFun(this.info.createTime)) : mobilePhoneList;
          const updateTimeList = String(this.info.updateTime).length > 0 ? createTimeList.filter(item => item.updateTime == this.formatterFun(this.info.updateTime)) : createTimeList;
          this.newDataList = JSON.parse(JSON.stringify(updateTimeList));
        } else {
          this.$message("请您选择要筛选的条件");
        }
      },
      async getUserList() {
        try {
          this.loading = true;
          const { code, result: { users, totalCount } } = await getUserList({
            pageNo: this.pageNo,
            pageSize: this.pageSize
          });
          if (code == 0) {
            this.loading = false;
            this.count = totalCount;
            this.list = JSON.parse(JSON.stringify(users));
            this.list.forEach(item => {
              item.createTime = this.formatterFun(item.createTime);
              item.updateTime = this.formatterFun(item.updateTime);
            });
            this.list.sort((firstItem, lastItem) => firstItem.id - lastItem.id);
            // 邮箱数组
            let emailDataArr = [];
            this.emailList = [];
            this.list.forEach(item => {
              if (emailDataArr.indexOf(item.email) == -1) {
                emailDataArr.push(item.email);
                this.emailList.push(item);
              }
            });
            // 手机号数组
            let mobilePhoneList = [];
            this.mobilePhoneList = [];
            this.list.forEach(item => {
              if (mobilePhoneList.indexOf(item.email) == -1) {
                mobilePhoneList.push(item.email);
                this.mobilePhoneList.push(item);
              }
            });
            this.newDataList = JSON.parse(JSON.stringify(this.list));
          }
        } catch (error) {
          console.log("用户列表接口报错了", error);
        }
      },
      formatterFun(time) {
        return `${new Date(time).getFullYear()}-${new Date(time).getMonth() + 1}-${new Date(time).getDate()}`;
      },
      handleFormatter(row) {
        return `${new Date(row.createTime).getFullYear()}-${new Date(row.createTime).getMonth() + 1}-${new Date(row.createTime).getDate()}`;
      },
      handleFormatter2(row) {
        return `${new Date(row.updateTime).getFullYear()}-${new Date(row.updateTime).getMonth() + 1}-${new Date(row.updateTime).getDate()}`;
      },
    }
  };
</script>

<style lang="scss">
  .user_list {
    height: 100%;
    padding-bottom: 20px;
    box-sizing: border-box;

    .juads_div {
      height: calc(100vh - 229px);
      margin-top: 20px;
      background-color: #fff;
      box-sizing: border-box;
      padding: 20px;
    }

    .table_div {
      height: calc(100vh - 250px);
    }

    .fenye_div {
      margin-top: 30px;
      text-align: right;
    }

    .top_span2 {
      /** 文本1 */
      font-size: 14px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
    }

    .sx_top {
      height: 120px;
      background-color: #fff;
      box-sizing: border-box;
      padding-left: 36px;
      padding-top: 23px;
    }

    .btn {
      display: flex;
      justify-content: center;
      margin-top: 140px;
    }
  }
</style>